<template>
    <div class="cardContent">
        <a-form layout="inline"
                :model="searchData">
            <a-form-item>
                <a-input v-model:value="searchData.title" placeholder="标题"></a-input>
            </a-form-item>
            <a-form-item>
                <a-select
                        ref="select"
                        v-model:value="searchData.productId"
                        placeholder="产品"
                        style="width: 120px"
                        :options="allProductList"
                        :field-names="{label:'name',value:'id'}"
                ></a-select>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" @click="load(1)">搜索</a-button>
            </a-form-item>
            <a-form-item>
                <a-button type="default" @click="rest">重置</a-button>
            </a-form-item>
        </a-form>
    </div>
    <div class="cardContent">
        <a-button type="primary" @click="openModal({},'新增')">新增</a-button>
        <a-table :dataSource="salesOrderList"
                 :columns="columns"
                 :pagination="false"
                 bordered>
            <template #status="{text,record}">
                <a-tag v-if="text == 0" color="default">
                    <template #icon>
                        <clock-circle-outlined/>
                    </template>
                    等待工作人员处理
                </a-tag>
                <a-tag v-if="text == 1" color="processing">
                    <template #icon>
                        <sync-outlined :spin="true"/>
                    </template>
                    打包出库中
                </a-tag>
                <a-tag v-if="text == 2" color="success">
                    <template #icon>
                        <check-circle-outlined/>
                    </template>
                    出库成功
                </a-tag>
            </template>
            <template v-slot:action="{text,record}">
                <a-space>
                    <a-button type="primary" v-if="record.status == 0" @click="openModal(record,'编辑')">编辑</a-button>
                    <a-popconfirm
                            title="删除数据无法恢复，请确认是否删除？"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button v-if="record.status == 0" type="danger">删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
        <a-config-provider :locale="locale">
            <a-pagination style="margin-top: 10px; text-align: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onChange"/>
        </a-config-provider>
    </div>
    <a-drawer
            :title="drawerTitle"
            :width="1000"
            :visible="visible"
            :body-style="{ paddingBottom: '40px' }"
            :footer-style="{ textAlign: 'right' }"
            @close="visible = false"
    >
        <a-form layout="vertical" :model="salesOrder">
            <a-row :gutter="16">
                <a-col :span="16">
                    <a-form-item
                            label="标题"
                            name="title" v-bind="validateInfos.title">
                        <a-input v-model:value="salesOrder.title"/>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="创建人">
                        <a-input v-model:value="loginUser.username" disabled/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item
                            label="销售商品" v-bind="validateInfos.productId">
                        <a-select
                                v-if="drawerTitle == '新增'"
                                ref="select"
                                v-model:value="salesOrder.productId"
                                placeholder="请选择"
                                :options="productList"
                                :field-names="{label: 'name',value: 'id'}"
                                @change="onSelected"
                        ></a-select>
                        <a-input v-else v-model:value="salesOrder.productName" disabled/>
                    </a-form-item>
                </a-col>
                <a-col :span="6">
                    <a-form-item label="交易量" v-bind="validateInfos.volume">
                        <a-input-number v-model:value="salesOrder.volume"
                                        addon-after="件"
                                        :min="product.minTradingVolume"
                                        :max="product.num"/>
                    </a-form-item>
                </a-col>
                <a-col :span="6">
                    <a-form-item label="成交额">
                        <a-input-number addon-after="￥" v-model:value="turnover" disabled/>
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item
                            label="交易描述"
                            name="remark">
                        <a-textarea :auto-size="{minRows:3}" v-model:value="salesOrder.remark"/>
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item>
                        <a-space>
                            <a-button type="primary" @click="submitOk">
                                提交
                            </a-button>
                            <a-button type="default" @click="resetFields">
                                重置
                            </a-button>
                        </a-space>

                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-drawer>
</template>

<script>
    import {ref, onMounted, computed} from 'vue'
    import axios from 'axios'
    import {message, Form} from 'ant-design-vue';
    import {SyncOutlined, ClockCircleOutlined, CheckCircleOutlined} from '@ant-design/icons-vue'
    import store from '@/store'
    import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
    import {isEmpty} from "@/utils/Tool";


    export default {
        name: "sales-salesOrder",
        components: {
            SyncOutlined,
            ClockCircleOutlined,
            CheckCircleOutlined
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                },
                {
                    title: '标题',
                    dataIndex: 'title',
                    key: 'title',
                },
                {
                    title: '产品',
                    dataIndex: 'productName',
                    key: 'productName',
                },
                {
                    title: '成交量',
                    dataIndex: 'volume',
                    key: 'volume',
                },
                {
                    title: '总售价',
                    dataIndex: 'turnover',
                    key: 'turnover',
                },
                {
                    title: '创建人',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    slots: {customRender: 'status'},
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: {customRender: 'action'},
                    align: 'center'
                }
            ]

            const salesOrder = ref({
                title: '',
                productId: '',
                volume: '',
                // remark: '',
            })
            const locale = zhCN
            const useForm = Form.useForm
            const loginUser = ref({})
            const salesOrderList = ref()
            const productList = ref([])
            const product = ref({})
            const allProductList = ref([])
            const searchData = ref({})
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])
            const {validate, validateInfos, resetFields} = useForm(salesOrder, {
                title: [{required: true, message: '标题不能为空', trigger: ['change']}],
                productId: [{required: true, message: '请选择商品', trigger: ['change']}],
                volume: [{required: true, message: '请输入交易数量', trigger: ['change']}],
                // remark: [{required: true, message: '销售详情不能为空', trigger: ['submit', 'change']}],
            })

            const visible = ref(false);
            const drawerTitle = ref('');
            const turnover = computed(() => {
                if (isEmpty(product) || isEmpty(salesOrder.value.volume)) {
                    return 0
                } else {
                    return Number(product.value.price * product.value.discount * salesOrder.value.volume).toFixed(2)
                }
            })

            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('sales-order/queryByCondition', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        title: searchData.value.title,
                        productId: searchData.value.productId,
                        userId: searchData.value.userId
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    salesOrderList.value = rs.data.records
                    pagination.value.total = rs.data.total
                })
            }

            const rest = () => {
                searchData.value = {}
                load()
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                load()
            }

            const openModal = (obj, message) => {
                console.log("模态框参数：", obj)
                salesOrder.value = JSON.parse(JSON.stringify(obj))
                if (message == '新增') {
                    resetFields()
                    axios.get('product/queryActiveProduct').then(rs => {
                        productList.value = rs.data
                        drawerTitle.value = '新增'
                        visible.value = true;
                    })
                } else {
                    axios.get('product/queryById/' + salesOrder.value.productId).then(rs => {
                        product.value = rs.data
                        drawerTitle.value = '编辑'
                        visible.value = true;
                    })
                }
            }

            const onSelected = (val, option) => {
                product.value = option
            }

            const submitOk = () => {
                validate().then(() => {
                    console.log("通过校验")
                    salesOrder.value.turnover = turnover.value
                    if (drawerTitle.value == '新增') {
                        salesOrder.value.userId = loginUser.value.id
                        salesOrder.value.status = 0
                    }
                    axios.post('/sales-order/saveOrUpdate', salesOrder.value).then(rs => {
                        console.log("新增或修改结果：", rs)
                        if (rs.code == 200) {
                            message.success("操作成功")
                            visible.value = false
                            load()
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch((e) => {
                    console.log("校验失败",e)
                })
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('salary/deleteById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.message)
                    }
                })
            }


            onMounted(() => {
                loginUser.value = store.state.user
                axios.get('product/queryAll').then(rs => {
                    allProductList.value = rs.data
                })
                load()
            })
            return {
                columns,
                pagination,
                searchData,
                load,
                rest,
                openModal,
                visible,
                okDelete,
                salesOrder,
                salesOrderList,
                productList,
                submitOk,
                validateInfos,
                resetFields,
                onChange,
                locale,
                pageSizeOptions,
                allProductList,
                drawerTitle,
                product,
                loginUser,
                onSelected,
                turnover
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }
</style>